import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/models/search_info_bean.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/circle/related_shop_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../base_view.dart';

class ShopList extends StatefulWidget {
  String title;
  String code;
  List<HaowuProduct> shopCart;

  ShopList(this.title, this.code, this.shopCart);

  @override
  _ShopListState createState() => _ShopListState();
}

class _ShopListState extends State<ShopList> {

  @override
  Widget build(BuildContext context) {
    return BaseView(
        model: RelatedShopModel(api: Provider.of(context)),
        onModelReady: (model) async {
          RelatedShopModel shopModel=model as RelatedShopModel;
          SearchInfoBean bean=SearchInfoBean(categoryCode: widget.code,pageSize: 20,pageNo: 1);
          if(widget.shopCart!=null&&widget.shopCart.isNotEmpty){
            //缓存列表用于打勾状态和最后提交返回上个页面，shopList只用于展示
            shopModel.cachedList=widget.shopCart;
          }
          shopModel.getShopList2(bean,0);
        },
        builder: ((context, model, child) => Scaffold(
              appBar: AppBar(
                backgroundColor: Colors.white,
                elevation: 0,
                //去除阴影
                brightness: Brightness.light,
                //黑色状态栏
                leading: IconButton(
                    onPressed: () {
                      Application.router.pop(context, model.getReturnShopList());
                    },
                    icon: Icon(
                      Icons.arrow_back_ios,
                      color: ColorsConfig.c_2c2c2c,
                    )),
                title: Text(
                  "选择商品",
                  style: TextStyle(color: ColorsConfig.c_2c2c2c,fontWeight: FontWeight.bold,fontSize: ScreenUtil().setSp(20)),
                ),
                centerTitle: true,
              ),
              body: WillPopScope(
                  child: Column(
                    children: [
                      _topTitle(widget.title, model),
                      _shop(model)
                    ],
                  ),
                  onWillPop: () async{
                    Application.router.pop(context, model.getReturnShopList());
                    return true;
                  }),
            )));
  }

  Widget _topTitle(String title, RelatedShopModel viewModel) {
    int num=viewModel.shopList!=null&&viewModel.shopList.isNotEmpty&&
    viewModel.shopList.length>0?viewModel.shopList.length:0;
    return Container(
        padding: EdgeInsets.symmetric(
            vertical: ScreenUtil().setWidth(20),
            horizontal: ScreenUtil().setWidth(15)),
        color: Colors.white,
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: ColorsConfig.c_2c2c2c,
                  fontSize: ScreenUtil().setSp(18)),
            ),
            // Text('($num)件',
            //     style: TextStyle(
            //         color: ColorsConfig.c_802c2c2c,
            //         fontSize: ScreenUtil().setSp(16)))
          ],
        ));
  }

  Widget _shop(RelatedShopModel viewModel) {
    return Expanded(
        child: EasyRefresh(
          enableControlFinishRefresh: true,
      enableControlFinishLoad: true,
      footer: ClassicalFooter(
          loadedText: "加载完成",
          loadingText: '加载中...',
          loadReadyText: "加载完成",
          loadText: "加载",
          loadFailedText: "加载失败",
          noMoreText: "没有更多了哦",
          infoText: "加载",
          bgColor: Colors.white,
          showInfo: false,
          textColor: Colors.black),
      header: ClassicalHeader(
        refreshingText: "刷新中...",
        refreshReadyText: "刷新",
        refreshText: "刷新",
        refreshedText: "刷新完成",
        refreshFailedText: "刷新失败",
        showInfo: false
      ),
      onLoad: () async {
        SearchInfoBean bean=SearchInfoBean(categoryCode: widget.code,pageNo: viewModel.pageNo,pageSize: 20);
        viewModel.getShopList2(bean, 2);
      },
      onRefresh: () async {
        viewModel.pageNo=1;
        viewModel.skuCode='';
        viewModel.clearShopList();
        viewModel.notifyListeners();
        SearchInfoBean bean=SearchInfoBean(categoryCode: widget.code,pageNo: viewModel.pageNo,pageSize: 20);
        viewModel.getShopList2(bean, 1);
      },
      child: ListView.builder(
          shrinkWrap: true,
          itemCount: viewModel.shopList != null ? viewModel.shopList.length : 0,
          itemBuilder: (value, index) {
            return _buildShop(viewModel, index);
          }),
          controller: viewModel.refreshController,
    ));
  }

  _buildShop(RelatedShopModel provide, int index) {
    StringBuffer pictureBaseUrl=StringBuffer();
    if(provide.shopList[index].picture!=null&&!provide.shopList[index].picture.startsWith('http')){
      pictureBaseUrl.write(OssHelper.pictureBaseUrl);
      pictureBaseUrl.write(provide.shopList[index].picture);
    }else{
      pictureBaseUrl.write('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603966641602&di=59dc495e8c57f2da98719f80d1d816c2&imgtype=0&src=http%3A%2F%2Fpic6.58cdn.com.cn%2Fmobile%2Fbig%2Fn_v242f9dea1883642f49bf07935db6d95ca.jpg%3Fw%3D425%26h%3D320');
    }
    return Container(
      color: Colors.white,
      width: double.infinity,
      height: ScreenUtil().setWidth(100),
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(15), 0, ScreenUtil().setWidth(15), 0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              margin: EdgeInsets.only(right: ScreenUtil().setWidth(14)),
              color: Colors.white,
              child: Image.network(
                pictureBaseUrl.toString(),
                width: ScreenUtil().setWidth(70),
                height: ScreenUtil().setWidth(70),
              )),
          Expanded(
              child: Column(
            children: [
              Expanded(
                  child: Container(
                      alignment: Alignment.topLeft,
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(15)),
                      color: Colors.white,
                      child: Text(
                          provide.shopList != null
                              ? provide.shopList[index].productName
                              : "",
                          maxLines: 2,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: ScreenUtil().setSp(16),
                              color: ColorsConfig.c_2c2c2c)))),
              Container(
                  margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(10)),
                  child: Row(
                    children: [
                      Text("￥",
                          style: TextStyle(
                              color: ColorsConfig.c_cd0000,
                              fontSize: ScreenUtil().setSp(12))),
                      Expanded(
                          child: Text(
                              provide.shopList != null &&
                                      provide.shopList[index].priceData != null
                                  ? provide.shopList[index].priceData.price.toStringAsFixed(2)
                                  : "0.00",
                              style: TextStyle(
                                  color: ColorsConfig.c_cd0000,
                                  fontSize: ScreenUtil().setSp(16)))),
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(right:ScreenUtil().setWidth(20)),
                          child: InkWell(
                              onTap: () {
                                provide.setChecked(index);
                              },
                              child: Opacity(
                                opacity: provide.shopList[index].isChecked?1.0:
                                  provide.greyButton?0.3:1,
                                child: Image.asset(
                                    provide.shopList != null &&
                                            provide.shopList[index].isChecked ==
                                                true
                                        ? 'picture/icon_choose.png'
                                        : 'picture/icon_add.png',
                                    package: 'amway_superapp_creator_plugin',
                                    width: ScreenUtil().setWidth(24),
                                    height: ScreenUtil().setWidth(24)),
                              )))
                    ],
                  ))
            ],
          ))
        ],
      ),
    );
  }
}
